package cn.accjiyun.gomoku.engine;

import cn.accjiyun.gomoku.model.ChessPoint;
import cn.accjiyun.gomoku.view.WinLine;

import java.util.Stack;

/**
 * Created by jiyun on 2016/9/18.
 */
public class CheckWin {
    
    private static Stack<ChessPoint> chessStack;
    private static int[][] chessboard;

    public static WinLine CheckWin(Stack<ChessPoint> stack, int N) {  //计算四个方向的连续相同棋子数目
        if (stack.empty()) return null;
        chessboard = new int[N + 5][N + 5];
        chessStack = stack;
        updateForecastBoard();
        ChessPoint chessPoint = stack.peek();
        int pointX = chessPoint.getX(), pointY = chessPoint.getY(), nowPlayer = chessPoint.getRole();
        int i, upX = pointX, upY = pointY, downX = pointX, downY = pointY;
        /**
         * 横向检测
         */
        for (i = 1; pointX + i <= N && chessboard[pointX + i][pointY] == nowPlayer; i++) ;  //向右检查
        upX = pointX + i - 1;
        for (i = 1; pointX - i > 0 && chessboard[pointX - i][pointY] == nowPlayer; i++) ;   //向左检查
        downX = pointX - i + 1;
        if (upX - downX >= 4) {
            return (new WinLine(upX, pointY, downX, pointY));
        }
        /**
         * 纵向检测
         */
        for (i = 1; pointY + i <= N && chessboard[pointX][pointY + i] == nowPlayer; i++) ; //向下检查
        downY = pointY + i - 1;
        for (i = 1; pointY - i > 0 && chessboard[pointX][pointY - i] == nowPlayer; i++) ; //向上检查
        upY = pointY - i + 1;
        if (downY - upY >= 4) {
            return (new WinLine(pointX, upY, pointX, downY));
        }
        /**
         *   "\"斜检测
         */
        for (i = 1; pointX + i <= N && pointY + i <= N && chessboard[pointX + i][pointY + i] == nowPlayer; i++)
            ; //向右下检查
        downX = pointX + i - 1;
        downY = pointY + i - 1;
        for (i = 1; pointX - i > 0 && pointY - i > 0 && chessboard[pointX - i][pointY - i] == nowPlayer; i++) ; //向左上检查
        upX = pointX - i + 1;
        upY = pointY - i + 1;
        if (downX - upX >= 4 || downY - upY >= 4) {
            return (new WinLine(upX, upY, downX, downY));
        }
        /**
         *   "/"斜检测
         */
        for (i = 1; pointX + i <= N && pointY - i > 0 && chessboard[pointX + i][pointY - i] == nowPlayer; i++) ; //向右上检查
        upX = pointX + i - 1;
        upY = pointY - i + 1;
        for (i = 1; pointX - i > 0 && pointY + i <= N && chessboard[pointX - i][pointY + i] == nowPlayer; i++) ; //向左下检查
        downX = pointX - i + 1;
        downY = pointY + i - 1;
        if (upX - downX >= 4 || downY - upY >= 4) {
            return (new WinLine(upX, upY, downX, downY));
        }
        return null;
    }
    
    public static void updateForecastBoard() {
        for (ChessPoint chessPoint : chessStack) {
            chessboard[chessPoint.getX()][chessPoint.getY()] = chessPoint.getRole();
        }
    }
}
